from django.views import View
from django import http
from random import randint

from libs.captcha.captcha import captcha
from django.core.cache import caches
from utils.response_code import RETCODE
from celery_tasks.sms.tasks import send_sms_code
from .constants import SEND_SMS_CODE_INTERVAL, SMS_CODE_REDIS_EXPIRES


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        # 调用SDK生成图形验证码
        name, text, image_bytes = captcha.generate_captcha()
        # 创建redis的verify-codes数据库
        redis = caches['verify_codes']
        # 将图形验证码字符串内容存储到redis，过期时间设置为5分钟
        redis.set(uuid, text, 300)
        # 响应图形bytes数据给前端
        return http.HttpResponse(image_bytes, content_type="image/png")


class SMSCodeView(View):
    """短信验证码"""

    def get(self, request, mobile):
        # 接收查询参数
        query_dict = request.GET
        image_code_client = query_dict.get("image_code")
        uuid = query_dict.get('uuid')
        # 校验
        if all([image_code_client, uuid]) is False:
            return http.HttpResponseForbidden("缺少必传参数！")

        # 创建redis链接对象，获取redis数据库当前用户图形验证码，取出后立即删除
        redis = caches['verify_codes']
        image_code_redis = redis.get(uuid)
        redis.delete(uuid)
        # 验证图形验证码是否有效
        if image_code_redis is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已过期'})
        if image_code_redis.lower() != image_code_client.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码错误'})

        # 发短信
        # 1、先从redis获取发送标记，如果取到了标记，说明手机发送过短信
        send_flag = redis.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.SMSCODERR, 'errmsg': '手机频繁发送短信'})
        # 2、生成验证码
        sms_code = '%04d' % randint(0, 9999)
        print('验证码：' + sms_code)
        # 把验证码存储到redis数据库
        redis.set('sms_%s' % mobile, sms_code, SMS_CODE_REDIS_EXPIRES)
        # 存储一个标记，表示手机号已经发送过短信，标记有效期60s
        redis.set('send_flag_%s' % mobile, 1, SEND_SMS_CODE_INTERVAL)
        # 触发异步任务，利用容联云通讯发送短信验证码，开放阶段暂停

        # send_sms_code.delay(mobile, sms_code)

        print(redis.get('sms_%s' % mobile))
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '成功'})
